<?php
require_once APPPATH."models/model_dao.php";
class Model_newsgroup extends Model_dao {
	function Model_newsgroup() {
		// Call the Model constructor
		parent::Model_dao("tbl_news_gr");
	}

	/**
	 *
	 *
	 */
	function find($id) {
		$this->db->where("id", $id);
		$query = $this->db->get($this->_tbl_name);

		if ($query->num_rows() > 0) {
			return $query->first_row('array');
		}
		return null;
	}

	/**
	 *
	 *
	 */
	function fetch_all()
	{
		$this->db->order_by("sort");
		$query = $this->db->get($this->_tbl_name);

		if ($query->num_rows() > 0) {
			return $query->result_array();
		}
		return null;
	}

	/**
	 *
	 *
	 */
	function browse($keyword, $limit = 10, $offset = 0, $order_by = 'sort'){
		$this->db->select("{$this->_tbl_name}.*, count(tbl_news.gid) AS quantity");
		$this->db->from($this->_tbl_name);
		if(!empty($keyword)){
			$this->db->like('nam', $keyword);
		}
		$this->db->join('tbl_news', "tbl_news.gid = {$this->_tbl_name}.id", "left");
		$this->db->group_by("{$this->_tbl_name}.id");
		$this->db->order_by($order_by, "desc");
		$this->db->limit($limit, $offset);

		$query = $this->db->get();
		//echo $this->db->last_query();
		if ($query->num_rows() > 0) {
			return $query->result_array();
		}
		return null;
	}

	/**
	 *
	 *
	 */
	function browse_count($keyword){
		if(!empty($keyword)){
			$this->db->like('name', $keyword);
		}

		return $this->db->count_all_results($this->_tbl_name);
	}

	/**
	 *
	 *
	 */
	function insert_group($data)
	{
		$sort = $this->get_max_sort();
		$data['sort'] = $sort;
		$this->db->insert($this->_tbl_name, $data);
		$id = $this->db->insert_id();
		return $id;
	}

	/**
	 *
	 *
	 */
	function update_group($data, $id)
	{
		$this->db->where('id', $id);
		return $this->db->update($this->_tbl_name, $data);
	}

	/**
	 *
	 *
	 */
	function delete_group($id){
		// not detete item in group
		$this->db->where('id', $id);
		return $this->db->delete($this->_tbl_name);
	}

	/**
	 *
	 *
	 */
	function get_max_sort()
	{
		$this->db->select_max('sort');
		$query = $this->db->get($this->_tbl_name);
		if ($query->num_rows() > 0) {
			$first_row = $query->first_row('array');
			return $first_row['sort'];
		}
		return 0;
	}
	
	function count_all(){
		return $this->db->count_all_results($this->_tbl_name);
	}
	
	function get_newest(){
		$this->db->select_max('id');
		$query = $this->db->get($this->_tbl_name);
		if ($query->num_rows() > 0) {
			$first_row = $query->first_row('array');
			return $first_row['id'];
		}
		return 0;
	}
	
}
?>